//
//  WCNServiceTimeVC.m
//  WCN
//
//  Created by 杨鑫 on 15/7/9.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNServiceTimeVC.h"
//
#import "WCButton.h"
#import "WCNSetTimeCCell.h"
#import "WCNSetTimeHeaderCRV.h"
#import "MJRefresh.h"
//
#import "UINavigationItem+Offset.h"
//
#import "WCPopupLayerManager.h"
#import "WCDefaultManager.h"
#import "WCNetworkAccessManager.h"
//
#import "Macros.h"
#import "Constants.h"

static NSString *cellId = @"WCNSetTimeCCell";
static NSString *headerId = @"WCNSetTimeHeaderCRV";
static NSString *footerId = @"UICollectionReusableView";

@interface WCNServiceTimeVC ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSArray *times;
@property (strong, nonatomic) NSString *refreshUrl;
@property (strong, nonatomic) NSString *orderId;

@property (strong, nonatomic) NSString *selectedDate;
@property (strong, nonatomic) NSDictionary *selectedTime;

@end

@implementation WCNServiceTimeVC

- (instancetype)initWithOrderId:(NSString *)orderId
{
    self = [super init];
    if (self) {
        Account *account = [[WCDefaultManager shareMg] account];
        _refreshUrl = [NSString stringWithFormat:@"nursing/order/service/time/schedule/%@", account.stringId];
        _orderId = orderId;
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    self.title = @"选择时间";
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(saveTime) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    self.view.backgroundColor = kAppBg;
    
    //init UICollectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.itemSize = CGSizeMake((kScreenWidth-2.0f)/3.0f, 50);
    flowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 33);
    flowLayout.footerReferenceSize = CGSizeMake(kScreenWidth, kOnePX);
    //init UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavHeight)
                                                          collectionViewLayout:flowLayout];
    self.collectionView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    [collectionView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellWithReuseIdentifier:cellId];
    [collectionView registerNib:[UINib nibWithNibName:headerId bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    [self.view addSubview:collectionView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    __weak typeof(self) weakSelf = self;
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
    [self.collectionView.header beginRefreshing];
}

#pragma mark - Others

- (void)refresh
{
    [[WCNetworkAccessManager sharedMg] GET:self.refreshUrl parameters:nil success:^(NSDictionary *result){
        NSMutableArray *muTimes = [NSMutableArray array];
        for (NSDictionary *day in result[@"data"]) {
            NSMutableDictionary *muDay = [NSMutableDictionary dictionary];
            muDay[@"date"] = day[@"date"];
            
            NSMutableArray *muDayTimes = [NSMutableArray array];
            NSArray *dayTimes = day[@"timePeriods"];
            for (NSDictionary *dayTime in dayTimes) {
                if ([dayTime[@"appointed"] intValue] == 0 && [dayTime[@"overdue"] intValue] == 0) {
                    [muDayTimes addObject:dayTime];
                }
            }
            
//            if (muDayTimes.count > 0) {
                muDay[@"timePeriods"] = muDayTimes;
                [muTimes addObject:muDay];
//            }
        }
        
        self.times = muTimes;
        [self.collectionView reloadData];
    } failure:nil netError:nil always:^{
        [self.collectionView.header endRefreshing];
    }];
}

- (void)saveTime
{
    if (!self.selectedTime) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择时间" withView:self.view];
        return;
    }
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
    NSDictionary *params = @{@"orderId": self.orderId,
                             @"targetDate": self.selectedDate,
                             @"timePeriodId": self.selectedTime[@"timePeriodId"]};
    [[WCNetworkAccessManager sharedMg] POST:@"nursing/order/appointment/next" parameters:params success:^(NSDictionary *result){
        [[WCPopupLayerManager shareMg] showTextOnly:result[@"errMsg"] withView:self.view];
        [self.navigationController popViewControllerAnimated:YES];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:OrderDetailRefreshNotification object:nil];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.times.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *day = self.times[section];
    NSArray *dayTimes = day[@"timePeriods"];
    
    return dayTimes.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *day = self.times[indexPath.section];
    NSArray *dayTimes = day[@"timePeriods"];
    NSDictionary *time = dayTimes[indexPath.row];
    WCNSetTimeCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.timeLabel.text = time[@"timePeriod"];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        WCNSetTimeHeaderCRV *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        NSDictionary *day = self.times[indexPath.section];
        header.timeLabel.text = day[@"date"];
        return header;
    } else if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        footer.backgroundColor = kBorderColor;
        return footer;
    }
    
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *day = self.times[indexPath.section];
    NSArray *dayTimes = day[@"timePeriods"];
    
    self.selectedDate = day[@"date"];
    self.selectedTime = dayTimes[indexPath.row];
}

@end
